package com.ll19.thread.test.demo2ThreadLocal;

import java.util.Random;

/**
 * 
 * @author dachuan
 * 
 *         synchronized关键字都是用来锁住对象的，这个地方锁住了this，两个线程访问的都是同一个类实例，
 *         所以两个线程中的this都是指一个东西。整个程序无竞争，运行时间大约10秒
 * 
 */
public class ThreadDemo3 implements Runnable {
	Student student = new Student();

	public static void main(String[] agrs) {
		ThreadDemo3 td = new ThreadDemo3();
		Thread t1 = new Thread(td, "a"); 
		Thread t2 = new Thread(td, "b");
		t1.start();
		t2.start();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Runnable#run()
	 */
	public void run() {
		accessStudent();
	}

	public void accessStudent() {
		String currentThreadName = Thread.currentThread().getName();
		System.out.println(currentThreadName + " is running!");
		// System.out.println("first read age is:"+this.student.getAge());
		synchronized (this) {
			Random random = new Random();
			int age = random.nextInt(100);
			System.out.println("thread " + currentThreadName + " set age to:"
					+ age);
			this.student.setAge(age);
			System.out.println("thread " + currentThreadName
					+ " first read age is:" + this.student.getAge());
			try {
				Thread.sleep(5000);
			} catch (InterruptedException ex) {
				ex.printStackTrace();
			}
		}
		System.out.println("thread " + currentThreadName
				+ " second read age is:" + this.student.getAge());
	}
}
